/**
* @author: LiYaHui
* @date: 2021-11-05
* @description: 预警监控弹框
*/
import Vue from 'vue'
import Main from './Detail'

let MonitoringConstructor = Vue.extend(Main)

let current
let instances = []

const defaultOptions = {
  value: false
}

const defaultCallback = (action, instance) => {
  if (current) {
    let callback = current.callback
    if (typeof callback === 'function') {
      callback(action)
    }
    if (action === 'cancel') {
      instance.value = false
    }
  }
}

function show (data) {
  let instance = new MonitoringConstructor()
  instance.callback = defaultCallback
  instance.$mount()
  instance.action = ''

  let options = data.options
  for (let prop in options) {
    if (options.hasOwnProperty(prop)) {
      instance[prop] = options[prop]
    }
  }
  if (!options.callback) {
    instance.callback = defaultCallback
  }
  let oldCb = instance.callback
  instance.callback = (action, instance) => {
    oldCb(action, instance)
  }
  document.body.appendChild(instance.$el)
  instances.push(instance)
  Vue.nextTick(() => {
    instance.value = true
  })
  instance.$on('input', () => {
    close(instance.id)
    instance.value = false
  })
  let date = new Date(data.time).getTime()
  let currentDate = new Date().getTime()
  let diffDate = 600000 - (currentDate - date)
  if (diffDate > 0) {
    setTimeout(() => {
      close(instance.id)
      instance.value = false
    }, diffDate)
  }
}

const Monitoring = function (options, callback) {
  if (Object.prototype.toString.call(options).slice(8, -1) !== 'Object') {
    console.error('place pass correct options')
    return
  }
  if (options.callback && !callback) {
    callback = options.callback
  }
  instances.push({
    options: Object.assign({}, defaultOptions, options),
    callback: callback
  })

  show()
}

Monitoring.add = (options, callback) => {
  if (options.callback && !callback) {
    callback = options.callback
  }
  let isNo = instances.find(item => item.id === options.id)
  if (isNo) {
    return false
  }
  show({
    id: options.id,
    time: options.time,
    options: Object.assign({}, defaultOptions, options),
    callback: callback
  })
}

function close (id) {
  let index = -1
  const instance = instances.filter((instance, i) => {
    if (instance.id === id) {
      index = i
      return true
    }
    return false
  })[0]
  if (!instance) return

  instances.splice(index, 1)
}

export default Monitoring
